<script setup lang="ts">
import TableHead from './TableHead.vue'
import ReportPerson from './ReportPerson.vue'

import type { LoadListParams } from './types'
import useAll from './useAll'
import { useStatementStore } from '@/store'
import { uuid } from '@/utils'
import {
  loadEnergyConsumptionStructureSchedule,
  selectEnergyDiscountList,
} from '@/api/modules/enterpriseQuarterlyReport'

const currentValue = ref('')
const previousValue = ref('')

const calc = computed(() => {
  // 消费量中的“合计"
  const listsValue = lists.value.map(v => v.data)

  // 加工转换投入合计=火力发电投入+供热投入+原煤入洗投入+炼焦投入+炼油及煤制油投入+制气投入+天然气液化投入+加工煤制品投入
  const keys = [
    'thermalPowerGeneration',
    'heating',
    'rawCoalIsWashed',
    'coking',
    'refining',
    'gasProduction',
    'naturalGasLiquefaction',
    'processedCoalProducts',
  ]

  return {
    // 加工转换投入合计
    machiningConversion: listsValue.map((v) => {
      let result = 0
      keys.forEach((key) => {
        const target = v.find(x => x.key === key)
        const value = target ? +target.value : 0
        result += value
      })
      result = +result.toFixed(2)
      return Number.isFinite(result) && result > 0
        ? result
        : ''
    }),
    conversionOutputDiscount: listsValue.map((v) => {
      let result = 0
      const t1 = v.find(x => x.key === 'conversionOutput')
      const t2 = v.find(x => x.key === 'useScalingFactor')
      result = (t1 ? +t1.value : 0) * (t2 ? +t2.value : 0)
      result = +result.toFixed(2)
      return Number.isFinite(result) && result > 0
        ? result
        : ''
    }),
  }
})

const summary = computed(() => {
  const obj = {
    energyName: '能源合计',
    unitOfMeasurement: '',
    code: '40',
    referenceDiscountFactor: '',
  }
  const listsValue = lists.value.map(v => v.data)
  // 折标系数
  const sss = listsValue.map((v) => {
    const target = v.find(
      vv => vv.key === 'useScalingFactor',
    )
    return target ? target.value : ''
  })
  const { statementFlattenColumns: flattenColumns }
    = storeToRefs(useStatementStore())
  const props = flattenColumns.value.map(v => v.prop)
  const listsMap = props.reduce((acc, prop) => {
    if (
      ![
        'referenceDiscountFactor',
        'useScalingFactor',
        'machiningConversion',
        'conversionOutputDiscount',
      ].includes(prop)
    ) {
      acc[prop] = listsValue.map((v) => {
        const target = v.find(vv => vv.key === prop)
        return target ? target.value : ''
      })
    }
    return acc
  }, {} as any)
  // 加工转换投入合计
  listsMap.machiningConversion = [
    ...calc.value.machiningConversion,
  ]
  // 能源加工转换产出折标量（吨标准煤）
  listsMap.conversionOutputDiscount = [
    ...calc.value.conversionOutputDiscount,
  ]

  // ①消费量：
  // 工业生产消费量、火力发电、供热、原煤入洗、炼焦、炼油、制气、
  // 天然气液化、加工煤制品、能源加工转换产出、回收利用、能源加工转换产出折标量（吨标准煤）、
  // 分别=能源品种×采用折标系数（累加）；

  // 能源加工转换产出折标量（吨标准煤）合计数=上列值相加；
  const accumulate = (prop: string, withFactor?: any) => {
    const n = +listsMap[prop]
      .reduce((acc: number, v: any, i: number) => {
        acc
          += (Number.isFinite(+v) ? +v : 0)
          * (withFactor ? +sss[i]! || 1 : 1)
        return acc
      }, 0)
      .toFixed(2)
    return Number.isFinite(n) ? n : ''
  }
  const getValue = (prop: string): any => {
    if (
      [
        'industrialProduction',
        'thermalPowerGeneration',
        'heating',
        'rawCoalIsWashed',
        'coking',
        'refining',
        'gasProduction',
        'naturalGasLiquefaction',
        'processedCoalProducts',
        'conversionOutput',
        'recycleAndReuse',
      ].includes(prop)
    ) {
      // 工业生产消费量、火力发电、供热、原煤入洗、炼焦、炼油、制气、
      // 天然气液化、加工煤制品、能源加工转换产出、回收利用、能源加工转换产出折标量（吨标准煤）、
      return accumulate(prop, true)
    }
    else if (
      [
        'conversionOutputDiscount',
        'machiningConversion',
      ].includes(prop)
    ) {
      // 能源加工转换产出折标量（吨标准煤）合计数
      return accumulate(prop)
    }
  }
  const data = flattenColumns.value.map((v) => {
    let editable = true
    if (Object.keys(obj).includes(v.prop)) {
      editable = false
    }
    return {
      key: v.prop,
      // @ts-expect-error
      value: obj[v.prop] || getValue(v.prop),
      editable,
    }
  })

  return {
    uuid: uuid(),
    data,
  }
})

async function request(params: LoadListParams) {
  const res = await loadEnergyConsumptionStructureSchedule(
    params,
  )
  const { data, ...rest } = res
  if (!data || data.length === 0) {
    const energyDiscount: any
      = await selectEnergyDiscountList()
    return {
      data: energyDiscount.map((v: any) => ({
        energyName: v.energyName || '',
        unitOfMeasurement: v.unitOfMeasurement,
        useScalingFactor: Math.min(
          ...(v.referenceDiscountFactor || '')
            .split('-')
            .map((vv: any) => +vv),
        ),
        referenceDiscountFactor:
          v.referenceDiscountFactor || '',
        code: v.code,
      })),
    }
  }

  const findIndex = data.findIndex(
    (v: any) =>
      v.energyName === '能源合计' || v.code === '40',
  )
  if (findIndex > -1) {
    data.splice(findIndex, 1)
  }

  // Set currentValue & previousValue
  const item = data[0]
  if (item) {
    currentValue.value = String(
      item.consumptionThisYear || '',
    )
    previousValue.value = String(
      item.consumptionLastYear || '',
    )
  }
  return { data, ...rest }
}

const {
  columns,
  title,
  lists,
  informant,
  clickCallback,
  loadPrevList,

  report,
  saveStage,
  exportFile,
} = useAll(request, {
  transfer(
    data: any,
    {
      statementFlattenColumns: flattenColumns,
    },
  ) {
    const props = flattenColumns.map(v => v.prop)
    return data.map((v: any) => {
      return {
        uuid: uuid(),
        informant: {
          personInCharge: v.personInCharge,
          informer: v.informer,
          telephone: v.telephone,
          fillInDate: v.fillInDate,
        },
        data: props.map((vv) => {
          const editable = ![
            'energyName',
            'unitOfMeasurement',
            'code',
            'machiningConversion', // 加工转换投入合计
            'conversionOutputDiscount', // 能源加工转换产出折标量
            'total',
            'referenceDiscountFactor',
          ].includes(vv)
          return {
            key: vv,
            value: String(v[vv] || ''),
            editable,
            calculable: [
              'machiningConversion',
              'conversionOutputDiscount',
            ].includes(vv),
          }
        }),
      }
    })
  },
  getCalc(
    row: number,
    prop: string,
    value?: string | number | undefined,
  ) {
    return (
      calc.value[prop as keyof typeof calc.value]?.[row]
      || value
    )
  },
  assignExtraData(params, { data, state, illustrate }) {
    const item = data[0] || {}
    params.list.push({
      ...item,
      ...summary?.value?.data.reduce((acc, v) => {
        acc[v.key] = String(v.value || '')
        return acc
      }, {} as any),
      state,
      illustrate,
    })

    // 本年综合能源消费量（当量值）
    // 上年综合能源消费量（当量值）
    params.consumptionThisYear = currentValue?.value
    params.consumptionLastYear = previousValue?.value
  },
})
</script>

<template>
  <div
    class="height-100 statement-table position-relative overflow-hidden"
  >
    <slot
      name="title"
      :title="title"
      :report="report"
      :load-prev-list="loadPrevList"
      :save-stage="saveStage"
      :export-file="exportFile"
    >
      <h2 class="table-title">
        {{ title }}
      </h2>
    </slot>
    <div class="report-table-head">
      <table class="report-table">
        <TableHead
          :columns="columns"
          show-line-number
        />
      </table>
    </div>
    <ElScrollbar
      class="bg-color"
      style="height: calc(100% - 140px)"
      wrap-style="overflow-x: hidden;"
    >
      <table class="report-table">
        <tbody ref="tbody">
          <tr v-for="(item, i) in lists" :key="item.uuid">
            <th class="readonly width-40px line-number">
              {{ i + 1 }}
            </th>
            <td
              v-for="(d, index) in item.data"
              :key="item.uuid + index"
              :class="{ 'is-calculable': d.calculable }"
            >
              <div v-if="!d.editable" class="span-cell">
                {{
                  d.calculable
                    ? calc[
                      d.key as
                        | 'machiningConversion'
                        | 'conversionOutputDiscount'
                    ][i]
                    : d.value
                }}
              </div>
              <div v-else class="input-cell">
                <input
                  v-model="d.value"
                  type="text"
                  @click="clickCallback"
                >
              </div>
            </td>
          </tr>
          <tr class="readonly">
            <th class="readonly width-40px line-number">
              {{ lists.length + 1 }}
            </th>
            <td
              v-for="(item, index) in summary.data"
              :key="summary.uuid + index"
            >
              <div class="span-cell">
                {{ item.value }}
              </div>
            </td>
          </tr>
        </tbody>
      </table>
      <div class="fill-description">
        <div class="extra-fill flex">
          <div class="report-label">
            本年综合能源消费量（当量值）：
          </div>
          <div class="report-value">
            <input
              v-model="currentValue"
              type="text"
              class="report-input"
            >
          </div>
          <div class="report-unit">
            万吨标准煤
          </div>
          <div class="report-label">
            上年综合能源消费量（当量值）：
          </div>
          <div class="report-value">
            <input
              v-model="previousValue"
              type="text"
              class="report-input"
            >
          </div>
          <div class="report-unit">
            万吨标准煤
          </div>
        </div>
        <ReportPerson v-model="informant" />
        <p>说明：</p>
        <p>
          1．计算“能源加工转换产出”、“回收利用”指标使用的折算系数同表1-2
        </p>
        <p>2．主要逻辑审核关系：</p>
        <p class="padding-horizontal">
          (1)
          工业生产消费量与表1-2的工业生产消费量数值一致。
        </p>
        <p class="padding-horizontal">
          (2)
          加工转换投入合计=火力发电投入+供热投入+原煤入洗投入+炼焦投入+炼油及煤制油投入+制气投入+天然气液化投入+加工煤制品投入。
        </p>
        <p>
          3．能源合计=∑某种能源×某种能源折标准煤系数（不重复计算“其中”项）。
        </p>
      </div>
    </ElScrollbar>
  </div>
</template>

<style scoped>
.extra-fill {
  align-items: center;
  padding-top: 1rem;

  --height: 33px;
}

.report-label {
  font-weight: 600;
  color: #333;
}

.report-value {
  border-bottom: 1px solid #999;
}

.report-unit {
  margin-right: 1rem;
}

.report-value :deep(.el-input__inner) {
  border: none;
  background: transparent;
  height: auto;
  line-height: 1.15;
  padding: 0;
}

.report-input {
  border: none;
  outline: none;
  background: transparent;
  vertical-align: bottom;
}
</style>
